package com.voxel.sense.infomsg;


import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Build;
import android.os.Handler;
import android.os.Process;
import android.support.multidex.MultiDex;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import com.ansen.http.entity.HttpConfig;
import com.ansen.http.net.HTTPCaller;
import com.example.com.common.app.Application;
import com.example.com.common.utils.ActivityTack;
import com.example.com.common.utils.FileUtils;
import com.example.com.common.utils.L;
import com.tencent.bugly.crashreport.CrashReport;
import com.tencent.mmkv.MMKV;
import com.umeng.commonsdk.UMConfigure;
import com.umeng.message.IUmengRegisterCallback;
import com.umeng.message.PushAgent;
import com.umeng.message.UTrack;
import com.umeng.message.UmengMessageHandler;
import com.umeng.message.UmengNotificationClickHandler;
import com.umeng.message.entity.UMessage;
import com.voxel.sense.infomsg.broad.NetBroadcastReceiver;
import com.voxel.sense.infomsg.module.login.LoginActivity;
import com.voxel.sense.infomsg.utils.AppFileUtil;
import com.voxel.sense.infomsg.utils.manager.QueryConfigManager;

import org.android.agoo.xiaomi.MiPushRegistar;

import java.io.File;
import java.util.List;

import cyy.example.com.facotry.Factory;
import cyy.example.com.facotry.net.helper.DbHelper;
import cyy.example.com.facotry.share.SPEngine;

public class App extends Application {
    private static final long HEART_BEAT_RATE = 30 * 1000;//目前心跳检测频率为30s
    private static final String USER_TOKEN_ALICE_TYPE = "USER_TOKEN_ALICE_TYPE";
    private static final String PUSH_ALICE_REGION_CODE = "A"; //区域码类型别名
    public static String desc = "";
    private PushAgent mPushAgent;

    @Override
    public void onCreate() {
        super.onCreate();
        // 调用Factory进行初始化
        Factory.setup();
        //初始化mmkv
        MMKV.initialize(this);
//        腾讯bugly-bug收集sdk初始化
//        CrashReport.initCrashReport(getApplicationContext(), "76b7490ccf", L.isDebug);


        //todo:初始化推送服务
//        if (shouldInit()) {
//            MiPushClient.registerPush(this, CommonConstants.PUSH_ID, CommonConstants.PUSH_KEY);
//        }
        //网络变化广播监听
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            IntentFilter filter = new IntentFilter();
            filter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
            NetBroadcastReceiver netBroadcastReceiver = new NetBroadcastReceiver();
            //注册广播
            registerReceiver(netBroadcastReceiver, filter);
        }

        initUmengPush();
        initHTTPCaller();

    }


    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        MultiDex.install(this);
    }
    private void initHTTPCaller() {
        HttpConfig httpConfig = new HttpConfig();
        HTTPCaller.getInstance().setHttpConfig(httpConfig);
    }

    /**
     * 进程是否关闭
     *
     * @return
     */
    private boolean shouldInit() {
        ActivityManager am = ((ActivityManager) getSystemService(Context.ACTIVITY_SERVICE));
        List<ActivityManager.RunningAppProcessInfo> processInfos = am.getRunningAppProcesses();
        String mainProcessName = getPackageName();
        int myPid = Process.myPid();
        for (ActivityManager.RunningAppProcessInfo info : processInfos) {
            if (info.pid == myPid && mainProcessName.equals(info.processName)) {
                return true;
            }
        }
        return false;
    }

    /***
     * 外部获取单例
     *
     * @return Application
     */
    public static App getInstance() {
        return (App) Application.getInstance();
    }


    /**
     * @param type 0 正常注销，1被踢下线，2，其他原因
     */
    synchronized public void logout(int type) {
        //不再登录状态，无需执行操作
        if (!SPEngine.getSPEngine().isLoginState())
            return;

        //清除推送绑定的别名
        deletePushAliasById();
        //清除sp中的用户数据
        SPEngine.getSPEngine().setLoginState(false);
        SPEngine.getSPEngine().clearUserInfo();

        //通关管理栈关闭所有的活动
        ActivityTack.getInstanse().finishAll();
        Intent intent = new Intent(this, LoginActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

        //关闭数据库
        DbHelper.getInstance().closeDataBase();

        //跳转登录界面
        startActivity(intent);

    }

    public void doCleanCache() {
        //清除缓存临时文件
        File fileDir = AppFileUtil.getCacheDir();
        FileUtils.deleteDir(fileDir);
        //清除配置信息
        QueryConfigManager.getInstance().resetDatas();
    }

    /**
     * 关闭程序
     */
    public void exitApp() {
        ActivityTack.getInstanse().finishAll();
        new Thread() {
            @Override
            public void run() {
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.exit(0);
            }
        }.start();
    }


    /**
     * 初始化友盟
     */
    private void initUmengPush() {
        //友盟初始化
        UMConfigure.init(this, "5cb031f10cafb24fb0000b55", "Umeng", UMConfigure.DEVICE_TYPE_PHONE, "94bfbfa8bbbe6cca806c58e789f6cd66");
        //小米通道
        MiPushRegistar.register(this, "2882303761517690325", "5851769069325");
        UMConfigure.setLogEnabled(true);//日志
        UMConfigure.setEncryptEnabled(true);//日志是否加密
        PushAgent.getInstance(this).onAppStart();

        mPushAgent = PushAgent.getInstance(this);
        mPushAgent.setResourcePackageName("com.voxel.sense.infomsg");

        //注册推送服务，每次调用register方法都会回调该接口
        mPushAgent.register(new IUmengRegisterCallback() {
            @Override
            public void onSuccess(String deviceToken) {
                //注册成功会返回device token
                L.d("Umeng", "regist---------" + deviceToken);
            }

            @Override
            public void onFailure(String s, String s1) {
                L.d("Umeng", "regist---------" + s + "----" + s1);
            }
        });


        UmengNotificationClickHandler notificationClickHandler = new UmengNotificationClickHandler() {
            @Override
            public void dealWithCustomAction(Context context, UMessage msg) {
                Toast.makeText(context, msg.custom, Toast.LENGTH_LONG).show();
                L.d("Umeng", "dealWithCustomAction---------" + msg.toString());
            }
        };
        UmengMessageHandler messageHandler = new UmengMessageHandler() {
            /**
             * 透穿通知的回调方法
             * @param context
             * @param msg
             */
            @Override
            public void dealWithNotificationMessage(Context context, UMessage msg) {
                //调用super则会走通知展示流程，不调用super则不展示通知
                super.dealWithNotificationMessage(context, msg);
                String msgType = msg.extra.get("msgType");
                Factory.dispatchPush(Factory.getGson().toJson(msg.extra), msgType);
            }
        };
        mPushAgent.setNotificationClickHandler(notificationClickHandler);
        mPushAgent.setMessageHandler(messageHandler);
        setPushAlias();
    }

    /**
     * 设置推送别名
     */
    public void setPushAlias() {
        boolean loginState = SPEngine.getSPEngine().isLoginState();

        if (loginState) {
            setPushAliceToken();
            setPushAliceReginCode();
        }
    }

    private void setPushAliceToken() {
        String token = SPEngine.getSPEngine().getUserInfo().getSetMobileToken();
        mPushAgent.setAlias(token, USER_TOKEN_ALICE_TYPE, new UTrack.ICallBack() {
            @Override
            public void onMessage(boolean b, String s) {
                if (!b) {
                    new Handler(getMainLooper()).postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            if (SPEngine.getSPEngine().isLoginState()) {
                                setPushAliceToken();
                            }
                        }
                    }, 5000);
                }
            }
        });
    }

    private void setPushAliceReginCode() {
        String regionCode = SPEngine.getSPEngine().getUserInfo().getRegionCode();
        if (regionCode == null) return;
        mPushAgent.setAlias(regionCode, PUSH_ALICE_REGION_CODE, new UTrack.ICallBack() {
            @Override
            public void onMessage(boolean b, String s) {
                if (!b) {
                    new Handler(getMainLooper()).postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            if (SPEngine.getSPEngine().isLoginState()) {
                                setPushAliceReginCode();
                            }
                        }
                    }, 5000);
                }
            }
        });
    }

    //删除别名
    private void deletePushAliasById() {
        String token = SPEngine.getSPEngine().getUserInfo().getSetMobileToken();
        String regionCode = SPEngine.getSPEngine().getUserInfo().getRegionCode();
        if (!TextUtils.isEmpty(token)) {
            mPushAgent.deleteAlias(regionCode, PUSH_ALICE_REGION_CODE, new UTrack.ICallBack() {
                @Override
                public void onMessage(boolean b, String s) {

                }
            });

            mPushAgent.deleteAlias(token, USER_TOKEN_ALICE_TYPE, new UTrack.ICallBack() {
                @Override
                public void onMessage(boolean b, String s) {
                }
            });
        }
    }

}
